package com.mininglamp.app.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@MapperScan("com.mininglamp.app.dao")
public class MybatisConfigure {

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource getDataSource() {
		return new DataSource();
	}

	@Bean
	public SqlSessionFactory getSqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(getDataSource());
		PathMatchingResourcePatternResolver resolve = resolver();
		MybatisProperties mybatisProperties = this.getMybatisProperties();
		sqlSessionFactoryBean.setConfigLocation(resolve.getResource(mybatisProperties.getConfigLocation()));
		sqlSessionFactoryBean.setMapperLocations(resolve.getResources(mybatisProperties.getMapperLocations()[0]));
		return sqlSessionFactoryBean.getObject();
	}

	@Bean
	@Primary
	@ConfigurationProperties(prefix = "mybatis")
	public MybatisProperties getMybatisProperties() {
		return new MybatisProperties();
	}

	@Bean
	public PathMatchingResourcePatternResolver resolver() {
		return new PathMatchingResourcePatternResolver();
	}

	@Bean
	public PlatformTransactionManager transactionManager() {
		return new DataSourceTransactionManager(getDataSource());
	}

}
